package com.example.demo.repository;

import com.example.demo.entity.SaleOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 销售订单数据访问层
 */
@Repository
public interface SaleOrderRepository extends JpaRepository<SaleOrder, Long> {
    
    Optional<SaleOrder> findByOrderNumber(String orderNumber);
    
    List<SaleOrder> findByCustomerId(Long customerId);
    
    List<SaleOrder> findByCashierId(Long cashierId);
    
    List<SaleOrder> findByStatus(SaleOrder.OrderStatus status);
    
    @Query("SELECT s FROM SaleOrder s WHERE s.orderTime BETWEEN :startTime AND :endTime")
    List<SaleOrder> findByOrderTimeBetween(@Param("startTime") LocalDateTime startTime, 
                                         @Param("endTime") LocalDateTime endTime);
    
    @Query("SELECT s FROM SaleOrder s WHERE s.cashierId = :cashierId AND s.orderTime BETWEEN :startTime AND :endTime")
    List<SaleOrder> findByCashierIdAndOrderTimeBetween(@Param("cashierId") Long cashierId,
                                                      @Param("startTime") LocalDateTime startTime,
                                                      @Param("endTime") LocalDateTime endTime);
    
    @Query("SELECT SUM(s.finalAmount) FROM SaleOrder s WHERE s.orderTime BETWEEN :startTime AND :endTime")
    Double getTotalSalesByDateRange(@Param("startTime") LocalDateTime startTime,
                                   @Param("endTime") LocalDateTime endTime);
    
    boolean existsByOrderNumber(String orderNumber);
}
